package com.lanou.renrenxin.custommodule;

import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.support.v4.app.FragmentTabHost;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TabHost;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by zy on 16/3/2.
 * 自定义标准导航栏
 */
public class SimpleTabHost implements TabHost.OnTabChangeListener {
    private FragmentTabHost fragmentTabHost;
    private LayoutInflater layoutInflater;
    private Resources resources;
    private ArrayList<NsFragmentItem> tabs;
    private NsFragmentItem preItem;

    SimpleTabHost(FragmentTabHost tabhost, ActionBarActivity activity) {
        this(tabhost, activity, android.R.id.tabcontent);
    }

    SimpleTabHost(FragmentTabHost tabhost, ActionBarActivity activity,
                  int realContentid) {
        fragmentTabHost = tabhost;
        tabs = new ArrayList<NsFragmentItem>();
        layoutInflater = activity.getLayoutInflater();
        resources = activity.getResources();
        tabhost.setup(activity.getBaseContext(),
                activity.getSupportFragmentManager(), realContentid);
        tabhost.setOnTabChangedListener(this);
    }

    public View newTabView(int layoutid, int backgroung, String title) {
        TextView tv = (TextView) layoutInflater.inflate(layoutid, null);
        tv.setText(title);
        Drawable draw = resources.getDrawable(backgroung);
        tv.setCompoundDrawablesWithIntrinsicBounds(null, draw, null, null);
        return tv;
    }

    public void AddTab(NsFragmentItem item) {
        tabs.add(item);
        fragmentTabHost.addTab(fragmentTabHost.newTabSpec(item.tag)
                .setIndicator(item.view), item.fragment, null);
    }

    public NsFragmentItem getTabByTag(String tag) {
        for (NsFragmentItem item : tabs) {
            if (item.tag == tag) {
                return item;
            }
        }
        return null;
    }

    @Override
    public void onTabChanged(String tabId) {
        NsFragmentItem item = getTabByTag(tabId);
        if (item != null) {
            if (preItem != null) {
                preItem.view.setBackgroundResource(preItem.upStyle);
            }
            preItem = item;
            item.view.setBackgroundResource(item.downStyle);
        }
    }

    public static class NsFragmentItem {
        public View view;
        public String tag;
        public Class<?> fragment;
        public int downStyle;
        public int upStyle;
    }
}
